package top.someapp.applib.kits;

import androidx.annotation.NonNull;
import java.util.Objects;

/**
 * @author zwz
 * Created on 2020-03-31
 */
public class IPAddress {

    private int address;
    private String readable;

    public IPAddress(int address) {
        this.address = address;
        parse();
    }

    public static IPAddress of(int address) {
        return new IPAddress(address);
    }

    /// fixme: only support ipv4
    public static IPAddress of(@NonNull String address) {
        int value = 0;
        String[] parts = address.split("[.]");
        for (int i = 0, len = parts.length; i < len && value >= 0; i++) {
            String part = parts[i];
            value <<= 8;    // left shift 8 bits
            value &= (255 & Integer.valueOf(part));
        }
        return new IPAddress(value);
    }

    private void parse() {
        if (address == 0) {
            readable = "0.0.0.0";
            return;
        }
        StringBuilder sb = new StringBuilder(16);
        boolean first = true;
        for (int value = address; value > 0; ) {
            if (first) {
                first = false;
            } else {
                sb.append(".");
            }
            sb.append(value & 255);
            value >>= 8;    // right 8 bits;
        }
        readable = sb.toString();
    }

    public String getReadable() {
        return readable;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        IPAddress ipAddress = (IPAddress) o;
        return address == ipAddress.address;
    }

    @Override
    public int hashCode() {
        return Objects.hash(address);
    }

    @Override
    public String toString() {
        return getReadable();
    }
}
